// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate

const routes = db.collection('routes')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case 'list': {
      return list(event)
    }
    case 'detail': {
      return detail(event)
    }
    case 'detailAndDate': {
      return detailAndDate(event)
    }
    case 'add': {
      return add(event)
    }
    case 'update': {
      return update(event)
    }
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}

function Message(code = 1, msg = '', data = {}) {
  return {
    code,
    msg,
    data
  };
}
/**
 * 获取线路列表
 */
async function list(event) {
  let {
    OPENID
  } = cloud.getWXContext()
  const {
    result
  } = await cloud.callFunction({
    name: "user",
    data: {
      action: "getUser",
      openId: OPENID
    }
  })
  if (result.length == 0) {
    return Message(-10, "暂无绑定的路线")
  } else {
    const user = result[0];
    const list = await routes.aggregate().match({
      gid: _.in(user.groupID),
      type: event.type,
      status: 1
    }).project({
      _id: 1,
      number: 1,
      type: 1,
      plateNumber: 1,
      approvedNumberber: 1,
      start: $.arrayElemAt(['$stations', 0]),
      end: $.arrayElemAt(['$stations', -1]),
      stations: 1
    }).end();
    return Message(1, "", list.list)
  }
}
/**
 * 获取线路详情
 */
async function detail(event) {
  try {
    const route = await routes.doc(event.id).get();
    return Message(1, "", route.data)
  } catch (err) {
    return Message(-11, "暂无此的路线", err)
  }
}
/**
 * 获取线路的可预约日期数组
 */
async function detailAndDate(event){
  let result = await detail(event);
  const {code,data} = result;
  if(code == 1){
    //如果是周一到周五 则判断是不是工作日 并补上国家规定的加班日
    if([1,2,3,4,5].every(item=>data.week.includes(item))){
      result = await cloud.callFunction({
        name: 'holiday',
        data: {
          action: "getWorkingDay",
          lastTime:data.latestAppointmentTime
        }
      })
    }else{ //非周一至周五的 获取近一周的可预约日期
      result = await cloud.callFunction({
        name: 'holiday',
        data: {
          action: "getFreeDay",
          week:data.week,
          lastTime:data.latestAppointmentTime
        }
      })
    }
    data.dates = result.result.data;
    return Message(1,"",data);
  }else{
    return result;
  }
}